const app = getApp();
const { uploadFile } = app._require("utils/upload.file");
const { AskPage } = app._require('common/index');
const formMixin = app._require("mixins/form.mixin.js").default;
//util.js
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
AskPage({
  /**
   * 页面的初始数据
   */
  mixins: [formMixin],
  data: {
    formatter(type, value) {
      if (type === "year") {
          return `${value}年`;
      } else if (type === "month") {
          return `${value}月`;
      }else if (type === "day") {
          return `${value}日`;
      }
      // else if (type === "hour") {
      //     return `${value}时`;
      // }else if (type === "minute") {
      //     return `${value}分`;
      // }
      
      return value;
  },
    image_urls: [],
    check_box_items:[{"title":"按时完成","subtitle":"所属村","desc":"请选择所属村"},
                    {"title":"未完成","subtitle":"所属镇","desc":"请选择所属镇"},
                    {"title":"未按时完成","subtitle":"单位名称","desc":""}],

    pickItems:[],
    showPop:false,
    showDate:false,
    showStage:false,
    minDate: new Date((new Date().getFullYear() ), 0, 1).getTime(),
    maxDate: new Date((new Date().getFullYear() + 5), 10, 1).getTime(),
    currentDate: new Date().getTime(),
    resImg:[]
  },
  onLoad: function (options) {
    
    console.log(options);

    wx.setNavigationBarTitle({
      title: (options.name+"项目进度填报")??""
    }),
 
   this.setData({
     "projectId":options.id??"",
    })
    this.listStage(options.id);
    // this.projectDetails(options.id);
  },
  async listStage(id){
    const response = await this.$_server("project/listStage", {
      params: {
        id: "?id="+id},
  });
   let { data } = response;
    console.log(data);  
   var pickItems = [];
   try{
    data.data.forEach(element => {
      pickItems.push(element.name)
    });
    this.setData({
      "stageItems":data.data,
      "pickItems":pickItems
    })
   }catch(err) {

   }   
  
  },
  clickTime(){
    console.log("完成时间")
    this.setData({
      "showPop":true,
      "showDate":true,
      "showStage":false,
      "currentDate": new Date().getTime(),
    })
  },
  clickStage(e){
    // console.log(e);
    this.setData({
      "showPop":true,
      "showDate":false,
      "showStage":true
    })
  },
  cancel(){
    this.setData({
      "showPop":false,
      "showDate":false,
      "showStage":false
    })
  },
  choicekBoxAction(e){
    // console.log(e.currentTarget.dataset.index);
    let current_value =  e.currentTarget.dataset.index + 1;
    this.setData({
      current_check_box : e.currentTarget.dataset.index,
      "current_value":current_value
    });
  },
  processForm:function(data){
   this.uploadAction(data);
  },
  async uploadAction(res){
    let{procee_content,percent,process_tag,qes_content,time,write_content} = res.detail.value;
    // console.log(app.user.userInfo.id);
    // return
    let content = procee_content??"";
    let process = percent??"";
    let riskProblem = qes_content??"";
    let leaderComment = write_content??"";
    let stageId = this.data.stageId ??"";
    let completeTime = this.data.completeTime ??"";
    let resImg = this.data.resImg;
    let projectId = this.data.projectId;
    let current_value = this.data.current_value;
    let collectorId = app.user.userInfo.id ||"";

    let error_res = this.validateFiled([
      [stageId, { required:"请选择项目节点!"}],
      [content, { required: "请填写进度内容!" }],
      [process, { required: "请输入完成进度!" }],
      [completeTime, { required: "请选择完成时间!" }],
      // [current_value, { required:"请选择完成情况!"}],
      // [riskProblem, { required: "请填写存在风险和问题!" }],
      // [leaderComment, { required: "请填写批示内容!" }],
  ]);
   
    // console.log(error_res.re);
  if (!error_res.result) {
      wx.showToast({
          title: error_res.msg,
          icon: "none",
      });
      return 
  }
  if(resImg.length==0){
    wx.showToast({
      title: '请上传图片',
      icon:"none"
    })
    return
  }
    const response = await this.$_server("project/project", {
      data: {
        content: content,
        process: process,
        riskProblem:riskProblem,
        leaderComment:leaderComment,
        stageId:stageId,
        completeTime:completeTime,
        resImg:resImg,
        state:current_value,
        projectId:projectId,
        collectorId:collectorId
      },});
  let { data } = response;
  console.log(data);     

  wx.showToast({
    title: data.message,
    icon:"none"
  })     
  if(data.code!=200){
    return
  } 
  const pages = getCurrentPages();
  const prevPage = pages[pages.length - 2]; // 上一页
  prevPage.setData({
    "type":"reload"
  })

  this.projectDetails(projectId);

  },
  async projectDetails(projectId){

      const response = await this.$_server("project/pdetail", {
        params: {
          id: "?id=" + projectId 
        },
    });
     let { data } = response;  
      console.log(data);
     if(data.code != 200){
       wx.showToast({
         title: data.message,
         icon:"none"
       })
       return
     }

     //==>
   let reolaValue = { "process":data.data.process,
                      "stageProcess":data.data.stageProcess,
                      "stageCompleteStatus":data.data.stageCompleteStatus,
                      "resImg" : this.data.resImg};
  
     //==>缓存
     wx.setStorageSync('reolaValue', reolaValue);

  //回调刷新
  wx.navigateBack({
  delta: 0,
  })

  }, 
  deleteIndex(ret){
    // console.log(ret.detail.index);
    let index = ret.detail.index;
    var img_urls = this.data.image_urls;
    let resImg = this.data.resImg;
    // console.log(resImg);
    img_urls.splice(index,1);
    resImg.splice(index,1);
    this.setData({
      "resImg":resImg,
      "image_urls":this.data.image_urls
    })



  },
  clickChoseImgs(){
    var image_urls = this.data.image_urls;
    wx.chooseImage({
      count: 9-image_urls.length,
      sourceType: ['album', 'camera'],
      success: res=> {
        var tempFilePaths = res.tempFilePaths;
        this.upload(res.tempFiles);
        //tempFiles
        // console.log(res.tempFiles);
        // console.log(res.tempFilePaths);

        // console.log("tempFilePaths--->" + tempFilePaths);
        tempFilePaths.forEach(element => {
          image_urls.push(element);  
        });
        
        // console.log("image_urls--->"+image_urls);
        this.setData({
            "image_urls":image_urls 
        });

      },
    });
    


  },
  getCredentials() {
    return new Promise(async (resolve, reject) => {
        const response = await this.$_server("cosAuth");
        let { data } = response;
        if (data.code !== 200) {
            reject(data);
        }
        resolve(data.data);
    });
  },
  async upload(files) {
    wx.showLoading({
        title: "上传中...",
        mask: true,
    });
    try {
        const nowTime = new Date();
        const uploadList = files.map(file => ({
            dir: this.data.uploadImageProps.dir + nowTime.format("yyyy/MM/dd") + "/",
            filePath: file.path || "",
            size: file.size,
            _id: "choose",
        }));
        let curFiles = [];
        console.log("getCredentials",uploadList);
        const _response = await uploadFile(uploadList, {
            limit: 10 * 1024 * 1024,
            timeout: 60*1000,
            action: this.data.actionUrl,
            initAuth: this.getCredentials.bind(this),
            onReady: files => {
                this.triggerEvent("update", {
                    type: "upload",
                    list: files,
                    item: null,
                });
            },
            beforeUpload: (curFile, files) => {
                this.triggerEvent("update", {
                    type: "upload",
                    list: files,
                    item: curFile,
                });
            },
            afterUpload: (curFile, files, errors) => {
                if (errors && errors.length > 0) {
                    wx.askShowToastEx({
                        icon: "none",
                        title: "上传文件只能在" + 10 + "M以内",
                    });
                }
                curFiles.push(curFile);
                // console.log(curFile);
                // url = curFile;
                this.triggerEvent("update", {
                    type: "upload",
                    list: files,
                    item: curFile,
                });
            },
        });

        try{
          let resImg = this.data.resImg;
          curFiles.forEach(element => {
            resImg.push(element.fileName)
          });
          this.setData({
            "resImg":resImg
          })
        }catch(e){

        }
        // console.log(curFiles);
        wx.showToast({
          title: '上传成功',
          icon:"none"
        })
        
        wx.hideLoading();
    } catch (error) {
        wx.hideLoading();
        console.log(error);
    }
  },
  onConfirm(e){
    // app.util.formatTime(time);
    // console.log(e);
    // console.log( this.timestampToTime(e.detail));
    let completeTime = this.timestampToTime(e.detail);
    this.setData({
      "completeTime":completeTime
    }) 
    this.cancel()
  },
  confirm(e){
    let detail= e.detail;
    let index = detail.index;
    let item = this.data.stageItems[index];
    // console.log(item);
    this.setData({
      "stageId":item.id??"",
      "stageName":item.name??""
    })

    this.cancel()

  },
  timestampToTime(timestamp) {
    var date = new Date(timestamp );//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1):date.getMonth()+1) + '-';
    var D = (date.getDate()< 10 ? '0'+date.getDate():date.getDate())+ ' ';
    // var h = (date.getHours() < 10 ? '0'+date.getHours():date.getHours())+ ':';
    // var m = (date.getMinutes() < 10 ? '0'+date.getMinutes():date.getMinutes()) + ':';
    // var s = date.getSeconds() < 10 ? '0'+date.getSeconds():date.getSeconds();
    return Y+M+D;
  },
  getIntegral(e){
    // console.log(e.detail.value);
  }

})